package com.blog.servlet;

import com.blog.dao.ArticleDao;
import com.blog.dao.CategoryDao;
import com.blog.dao.impl.ArticleDaoImpl;
import com.blog.dao.impl.CategoryDaoImpl;
import com.blog.entity.Article;
import com.blog.entity.Category;
import com.blog.entity.User;
import com.blog.util.StringUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 文章发布/编辑Servlet
 */
@WebServlet("/article/edit")
public class ArticleServlet extends HttpServlet {
    private ArticleDao articleDao = new ArticleDaoImpl();
    private CategoryDao categoryDao = new CategoryDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 获取文章ID，判断是新增还是编辑
        String idStr = request.getParameter("id");

        if (idStr != null && !idStr.isEmpty()) {
            // 编辑文章：查询文章详情并回显
            try {
                int id = Integer.parseInt(idStr);
                Article article = articleDao.findById(id);

                // 验证文章所有者
                HttpSession session = request.getSession();
                User loginUser = (User) session.getAttribute("loginUser");
                if (article == null || article.getUserId() != loginUser.getId()) {
                    request.setAttribute("errorMsg", "无法找到该文章或没有权限编辑");
                    request.getRequestDispatcher("/error.jsp").forward(request, response);
                    return;
                }

                request.setAttribute("article", article);
            } catch (NumberFormatException e) {
                request.setAttribute("errorMsg", "参数错误");
                request.getRequestDispatcher("/error.jsp").forward(request, response);
                return;
            }
        }

        // 2. 查询所有分类（用于下拉选择）
//        List<Category> categoryList = categoryDao.findAll();
//        request.setAttribute("categoryList", categoryList);

        // 3. 转发到编辑页面
        request.getRequestDispatcher("/article/edit.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        // 1. 获取表单参数
        String idStr = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String categoryIdStr = request.getParameter("categoryId");
        String isPublishedStr = request.getParameter("isPublished");

        // 2. 参数校验
        if (StringUtil.isEmpty(title) || StringUtil.isEmpty(content) ||
                StringUtil.isEmpty(categoryIdStr) || StringUtil.isEmpty(isPublishedStr)) {
            request.setAttribute("errorMsg", "标题、内容和分类不能为空！");
            request.getRequestDispatcher("/article/edit.jsp").forward(request, response);
            return;
        }

        // 3. 转换参数类型
        int categoryId;
        int isPublished;
        try {
            categoryId = Integer.parseInt(categoryIdStr);
            isPublished = Integer.parseInt(isPublishedStr);
        } catch (NumberFormatException e) {
            request.setAttribute("errorMsg", "参数格式错误！");
            request.getRequestDispatcher("/article/edit.jsp").forward(request, response);
            return;
        }

        // 4. 获取当前登录用户
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        // 5. 创建Article对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setCategoryId(categoryId);
        article.setUserId(loginUser.getId());
        article.setIsPublished(isPublished);

        // 6. 判断是新增还是更新
        int rows = 0;
        if (idStr == null || idStr.isEmpty()) {
            // 新增文章
            rows = articleDao.add(article);
        } else {
            // 更新文章
            try {
                int id = Integer.parseInt(idStr);
                article.setId(id);
                rows = articleDao.update(article);
            } catch (NumberFormatException e) {
                request.setAttribute("errorMsg", "参数格式错误！");
                request.getRequestDispatcher("/article/edit.jsp").forward(request, response);
                return;
            }
        }

        // 7. 处理结果
        if (rows > 0) {
            // 操作成功，重定向到文章列表
            response.sendRedirect(request.getContextPath() + "/articles");
        } else {
            // 操作失败，返回编辑页面
            request.setAttribute("errorMsg", "保存文章失败，请重试！");
            request.setAttribute("article", article);

            // 重新查询分类列表
//            List<Category> categoryList = categoryDao.findAll();
//            request.setAttribute("categoryList", categoryList);

            request.getRequestDispatcher("/article/edit.jsp").forward(request, response);
        }
    }
}